namespace CloudNinja.Metering.Providers.SQLAzure
{
    using System;

    using CloudNinja.Metering.Common;
    using CloudNinja.Metering.Common.Logging;

    using Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling;

    public class TenantDatabaseSize
    {
        public static long GetDatabaseSize(string connStr, ILogger logger, IMeteringContext meteringContext)
        {
            using (var connection = new ReliableSqlConnection(connStr, meteringContext.SqlAzureConnectionRetryPolicy, meteringContext.SqlAzureCommandRetryPolicy))
            {
                using (var command = connection.CreateCommand())
                {
                    try
                    {
                        connection.Open();

                        // Get the total pages reserved for the database. A page is 8k in size, so multiply it by 8 to get the total reserved space in kiloBytes.
                        command.CommandText = @"SELECT SUM(reserved_page_count)* 8 FROM sys.dm_db_partition_stats";
                        command.CommandType = System.Data.CommandType.Text;

                        return (long)command.ExecuteScalarWithRetry(meteringContext.SqlAzureCommandRetryPolicy);
                    }
                    catch (Exception ex)
                    {
                        logger.LogException(ex);
                    }
                }
            }

            return 0;
        }
    }
}